package com.doradance.main.demo;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.doradance.R;
import com.hpplay.bean.CastDeviceInfo;
import com.hpplay.bean.MediaStateInfo;
import com.hpplay.bean.WebPushInfo;
import com.hpplay.callback.AuthorizationCodeCallBack;
import com.hpplay.callback.CastDeviceCallback;
import com.hpplay.callback.CastDeviceServiceCallback;
import com.hpplay.callback.ExecuteResultCallBack;
import com.hpplay.callback.HpplayWindowPlayCallBack;
import com.hpplay.callback.MirrorStateCallback;
import com.hpplay.callback.ScreenCodeCallBack;
import com.hpplay.callback.TransportCallBack;
import com.hpplay.link.HpplayLinkControl;

import java.util.ArrayList;
import java.util.List;

public class HpplayAPISDKActivity extends AppCompatActivity implements View.OnClickListener, CastDeviceCallback, ExecuteResultCallBack,TransportCallBack,ScreenCodeCallBack
{
    /**
     * 官网申请到的Key
     */
    private static final String mKey = "4a2fdac3756f54a783c51b4748a1fe66";
    private static final String TAG = "HpplayAPISDKActivity";

    private EditText mPlayUrlEdit;

    private HpplayLinkControl mHpplayLinkControl;
    private AuthorizationCodeCallBack mAuthorizationCodeCallBack;
    private MediaStateInfo mVideoInfo;

    private SeekBar mVolumeControlProcess;
    private SeekBar mPlayControlProcess;

    private EditText mEditTextUser;
    private EditText mEditTextSetting;
    private EditText mWebImageAddress;

    private boolean isPlay;
    private boolean isConnect;
    private boolean bAutoSendClickFlag=false;
    private boolean isClick = true;

    private List<CastDeviceInfo> mListDevice = new ArrayList<CastDeviceInfo>();
    private DeviceAdapter mDeviceAdapter;
    private ListView mListView;
    private ImageView mSelectImg;
    private static boolean isFirstConnect;
    private int mPosition = -1;
    private long			 	mPrevCastStopTimeStamp=0;
    private String     mCurConnDeviceName=null;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case 1:
                    showCurseDialog("播放地址不能为空");
                    break;

                case 2:
                    if (mVideoInfo == null) {
                        showCurseDialog("获取TV端状态失败");
                    } else {
                        Log.e("~~~~~~~~~~~~~~~~~",mVideoInfo.getPosition()+ "~~~~~~~~---------~~~~~~~~" +mVideoInfo.getDuration());
                        if (mVolumeControlProcess != null) {
                            mVolumeControlProcess.setMax(mVideoInfo.getVolumemax());
                            mVolumeControlProcess.setProgress(mVideoInfo.getCurrentvolume());
                            mPlayControlProcess.setMax(mVideoInfo.getDuration());
                            mPlayControlProcess.setProgress(mVideoInfo.getPosition());
                        }
                        String mSatet="";
                        if ((!mSatet.equals(mVideoInfo.getState())) ||"error".equals(mVideoInfo.getState())) {
                            mSatet = mVideoInfo.getState();
                            Toast.makeText(HpplayAPISDKActivity.this, "播放状态" + mSatet, Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case 4:
                    showCurseDialog("拒绝连接");
                    break;

                case 5:
                    Log.e(TAG,"-------onAuthorizationCode------111---"+isFinishing());

                    final EditText et = new EditText(HpplayAPISDKActivity.this);


                     try{
                         new AlertDialog.Builder(HpplayAPISDKActivity.this)
                                 .setTitle("请输入")
                                 .setIcon(android.R.drawable.ic_dialog_info)
                                 .setView(et)
                                 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                     public void onClick(DialogInterface dialog, int which) {
                                         String input = et.getText().toString();
                                         if (input.equals("") || input == null) {
                                             Toast.makeText(getApplicationContext(), "内容不能为空！" + input, Toast.LENGTH_LONG).show();
                                         }
                                         if(mAuthorizationCodeCallBack != null) {
                                             mAuthorizationCodeCallBack.onAuthorizationCode(input);
                                             mAuthorizationCodeCallBack = null;
                                         }
                                     }
                                 })
                                 .show();
                     }catch (Exception e){
                         e.printStackTrace();
                     }

                    break;


                case 10 :
                    showCurseDialog("镜像失败");
                    break;

                case 11 :
                    showCurseDialog("镜像成功");
                    break;

                case 12 :
                    showCurseDialog("镜像断开");
                    break;

                case 34 :
                    showCurseDialog("没有搜索到设备");
                    break;

                case 35 :
                    if(null!=mCurConnDeviceName)
                    {
                        showCurseDialog("已指定连接设备:"+mCurConnDeviceName);
                    }
                    else
                    {
                        showCurseDialog("已指定连接设备");
                    }
                    break;

                default:
                    break;
            }
        };
    };
    private int mWidth;
    private int mHeigh;

    private HpplayWindowPlayCallBack mHpplayWindowPlayCallBack= null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hpplay_api_layout);
        mHpplayLinkControl = HpplayLinkControl.getInstance();
        mHpplayLinkControl.setDebug(true);
        mHpplayLinkControl.initHpplayLink(this, mKey);
        initView();
        mHpplayLinkControl.setTransportCallBack(this);
    }

    private void initView() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;
        mHeigh = dm.heightPixels;
        mPlayUrlEdit = (EditText) findViewById(R.id.hpplay_play_url);
        findViewById(R.id.button_push_music).setOnClickListener(this);
        findViewById(R.id.button_mirror_status).setOnClickListener(this);
        findViewById(R.id.button_play_start).setOnClickListener(this);
        findViewById(R.id.button_play_pause).setOnClickListener(this);
        findViewById(R.id.button_decrease_volume).setOnClickListener(this);
        findViewById(R.id.button_play_exit).setOnClickListener(this);
        findViewById(R.id.button_increase_volume).setOnClickListener(this);
        findViewById(R.id.button_PlayStopAsSDKExit).setOnClickListener(this);
        findViewById(R.id.button_GetPlayStopAsSDKStatus).setOnClickListener(this);
        findViewById(R.id.button_push_video_api).setOnClickListener(this);
        findViewById(R.id.button_StopPushWebImage).setOnClickListener(this);
        findViewById(R.id.button_StartPushWebImage).setOnClickListener(this);
        findViewById(R.id.button_mdns_search).setOnClickListener(this);
        findViewById(R.id.button_start_mirror).setOnClickListener(this);
        findViewById(R.id.button_stop_mirror).setOnClickListener(this);
        findViewById(R.id.buttonoverlap).setOnClickListener(this);
        findViewById(R.id.buttonisbottom).setOnClickListener(this);
        findViewById(R.id.buttonsize).setOnClickListener(this);
        findViewById(R.id.buttonisshow).setOnClickListener(this);
        findViewById(R.id.buttonisplay).setOnClickListener(this);
        findViewById(R.id.buttonmaxline).setOnClickListener(this);
        findViewById(R.id.buttonalpha).setOnClickListener(this);
        findViewById(R.id.buttonspeed).setOnClickListener(this);
        findViewById(R.id.buttonsendtext).setOnClickListener(this);
        findViewById(R.id.buttonsenduser).setOnClickListener(this);


        mPlayControlProcess = (SeekBar) findViewById(R.id.play_control_process);
        mEditTextUser = (EditText) findViewById(R.id.user_edittext);
        mEditTextSetting = (EditText) findViewById(R.id.user_setting_edittext);
        mWebImageAddress = (EditText) findViewById(R.id.webImage_Address);
        mVolumeControlProcess = (SeekBar) findViewById(R.id.volume_control_process);
        mVolumeControlProcess.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(final SeekBar seekBar) {
                mHpplayLinkControl.castDeviceVolume(HpplayAPISDKActivity.this,
                        1,seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser)
            {

            }
        });

        mPlayControlProcess.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(final SeekBar seekBar)
            {
                mHpplayLinkControl.castSeek(HpplayAPISDKActivity.this, 2,seekBar.getProgress());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar)
            {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, final int progress, boolean fromUser)
            {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出整个通信并释放
        mHpplayLinkControl.castDisconnectDevice();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("---------","----onActivityResult-------");
        mHpplayLinkControl.castStartMirrorResult(requestCode,resultCode,data);
    }
    //
    @Override
    public void onClick(View v) {
        String mVideoPlayingUrl=null;
        String size = mEditTextSetting.getText().toString();
        int sizeTpye = 13;
        switch (v.getId())
        {
            case R.id.button_push_music:
                //开始播放
                mVideoPlayingUrl = mPlayUrlEdit.getText().toString();
                if (mVideoPlayingUrl == null || TextUtils.isEmpty(mVideoPlayingUrl)) {
                    mVideoPlayingUrl = "http://so1.111ttt.com:8282/2016/5/12m/05/205051438013.m4a?tflag=1497429671&pin=39d0f31da48b98e7b48dac79b08f4443&ip=183.38.249.204#.mp3";
                }
                mHpplayLinkControl.castStartMediaPlay(HpplayAPISDKActivity.this, 1, mVideoPlayingUrl, HpplayLinkControl.PUSH_MUSIC);
                break;

            case R.id.button_mirror_status:
                boolean isOpen = mHpplayLinkControl.getMirrorState();
                showCurseDialog(isOpen?"镜像中":"镜像未开");
                break;

            case R.id.button_play_start:
                //开始播放
                mHpplayLinkControl.castPlayControl(HpplayAPISDKActivity.this, 4, true);
                break;

            case R.id.button_play_pause:
                //暂停播放
                mHpplayLinkControl.castPlayControl(HpplayAPISDKActivity.this, 5, false);
                break;

            case R.id.button_decrease_volume:
                //减小音量
                mHpplayLinkControl.castDeviceVolume(HpplayAPISDKActivity.this, 6, false);
                break;

            case R.id.button_play_exit:
                //退出播放
                mHpplayLinkControl.stopPlay(HpplayAPISDKActivity.this, 7);
                break;

            case R.id.button_increase_volume:
                //增加音量
                mHpplayLinkControl.castDeviceVolume(HpplayAPISDKActivity.this, 8, true);
                break;

            case R.id.button_PlayStopAsSDKExit:
                //TV端播放是否随应用退出
                mHpplayLinkControl.setIsBackgroundPlay(HpplayAPISDKActivity.this, 9, false);
                break;

            case R.id.button_GetPlayStopAsSDKStatus:
                mHpplayLinkControl.castDeviceCallback(HpplayAPISDKActivity.this);
                break;

            case R.id.button_push_video_api:
                bAutoSendClickFlag=false;
                String url="rtmp://live.hkstv.hk.lxdns.com/live/hks";
                mHpplayLinkControl.castStartMediaPlay(HpplayAPISDKActivity.this, 10, url, HpplayLinkControl.PUSH_VIDEO,13);
                break;

            case R.id.button_StartPushWebImage:
                String path = mWebImageAddress.getText().toString();

                if(path == null || TextUtils.isEmpty(path)){
                    showCurseDialog("地址为空,使用替代地址");
                    path ="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=" +
                            "1495016134108&di=330d67b42be445b2d060d2de61f62c35&imgtype=0&src=http%3A%2F%2Fpic31." +
                            "nipic.com%2F20130708%2F3822951_162441185000_2.jpg";
//                    path = "/storage/emulated/0/DCIM/Screenshots/Screenshot_2017-05-24-07-57-58-18.png";
                }
                mHpplayLinkControl.startPhotoPlay(HpplayAPISDKActivity.this,22,path);
                break;

            case R.id.button_StopPushWebImage:
                mHpplayLinkControl.stopPhotoPlay(HpplayAPISDKActivity.this,21);
                break;

            case R.id.button_mdns_search:
//                setCastView();
                //too offen will lead to app crash;
                if((0!=mPrevCastStopTimeStamp)&&(System.currentTimeMillis()-mPrevCastStopTimeStamp)<3000)
                {
                    Toast.makeText(HpplayAPISDKActivity.this,"投屏点击太频繁,请稍后重试",Toast.LENGTH_SHORT).show();
                    return;
                }
                mPrevCastStopTimeStamp=System.currentTimeMillis();
                mHpplayLinkControl.castServiceDiscovery(this, new CastDeviceServiceCallback()
                {
                    @Override
                    public void onNoneCastDeviceService()
                    {
                        Log.d(TAG,"castServiceDiscovery,onNoneCastDeviceService!!");
                        mHpplayLinkControl.castServiceStopDiscovery();
                        mHandler.sendEmptyMessage(34);
                    }

                    @Override
                    public void onCastDeviceServiceAvailable(List<CastDeviceInfo> list)
                    {
                        if(list.size()<=0)
                        {
                            Log.e(TAG,"castServiceDiscovery,castDevice list check failed!!");
                            return;
                        }
                        Log.d(TAG,"castServiceDiscovery,onCastDeviceServiceAvailable!!");
                        for (int i = 0;i< list.size();i++)
                        {
                            Log.d(TAG,"deviceName:"+list.get(i).getHpplayLinkName());
                        }

                        //这个是需要连接的设备名称;
                        mCurConnDeviceName=list.get(0).getHpplayLinkName();
                        mHpplayLinkControl.castConnectDevice(list.get(0),null);
                        mHpplayLinkControl.castServiceStopDiscovery();
                        mHandler.sendEmptyMessage(35);
                    }
                });
                break;
            case R.id.button_start_mirror:
                mHpplayLinkControl.castStartMirror(this, new MirrorStateCallback()
                {
                    @Override
                    public void onMirrorStarting() {

                    }

                    @Override
                    public void onMirrorFailed() {
                        mHandler.sendEmptyMessage(10);
                    }

                    @Override
                    public void onMirrorDisconnected() {
                        mHandler.sendEmptyMessage(12);
                    }

                    @Override
                    public void onMirrorConnected() {
                        mHandler.sendEmptyMessage(11);
                    }
                });
                break;

            case R.id.button_stop_mirror:
                mHpplayLinkControl.castStopMirror();
                break;


            case R.id.buttonoverlap:
                mHpplayLinkControl.setWebPushOverlap(HpplayAPISDKActivity.this, 11, isClick);
                isClick = !isClick;
                break;

            case R.id.buttonisbottom:
                mHpplayLinkControl.setWebPushIsBottom(HpplayAPISDKActivity.this, 12, isClick);
                isClick = !isClick;
                break;
            case R.id.buttonsize:

                if(size != null && !size.isEmpty()){
                    try{
                        sizeTpye = Integer.valueOf(size);
                    }catch (Exception e){
                        showCurseDialog("请输入数字类型");
                        return;
                    }
                }
                mHpplayLinkControl.setWebPushSize(HpplayAPISDKActivity.this, 13, sizeTpye);
                break;
            case R.id.buttonisshow:
                mHpplayLinkControl.setWebPushVisibility(HpplayAPISDKActivity.this, 14, isClick);
                isClick = !isClick;
                break;
            case R.id.buttonisplay:
                System.out.println("current status:"+isClick);
                if(bAutoSendClickFlag)
                {
                    isClick=false;
                    bAutoSendClickFlag=false;
                    mHpplayLinkControl.setWebPushPlay(HpplayAPISDKActivity.this, 15, isClick);
                    isClick = !isClick;
                }
                else
                {
                    mHpplayLinkControl.setWebPushPlay(HpplayAPISDKActivity.this, 15, isClick);
                    isClick = !isClick;
                }
                break;
            case R.id.buttonmaxline:
                if(size != null && !size.isEmpty()){
                    try{
                        sizeTpye = Integer.valueOf(size);
                    }catch (Exception e){
                        showCurseDialog("请输入数字类型");
                        return;
                    }
                }
                mHpplayLinkControl.setWebPushMaxLine(HpplayAPISDKActivity.this, 16, sizeTpye);
                break;
            case R.id.buttonalpha:
                if(size != null && !size.isEmpty()){
                    try{
                        sizeTpye = Integer.valueOf(size);
                    }catch (Exception e){
                        showCurseDialog("请输入数字类型");
                        return;
                    }
                }
                mHpplayLinkControl.setWebPushAlpha(HpplayAPISDKActivity.this, 17, sizeTpye);
                break;

            case R.id.buttonspeed:
                if(size != null && !size.isEmpty()){
                    try{
                        sizeTpye = Integer.valueOf(size);
                    }catch (Exception e){
                        showCurseDialog("请输入数字类型");
                        return;
                    }
                }
                mHpplayLinkControl.setWebPushSpeed(HpplayAPISDKActivity.this, 18, sizeTpye);
                break;

            case R.id.buttonsendtext:
                List<WebPushInfo> webPushList = new ArrayList<WebPushInfo>();
                for (int i = 1; i < 13; i++) {
                    WebPushInfo webPushInfo = new WebPushInfo();
                    webPushInfo.setContent("kkkkkkk"+i);
                    webPushInfo.setTextsize(50);
                    webPushInfo.setDelaytime(10);
                    webPushInfo.setType(1);
                    webPushList.add(webPushInfo);
                }
                mHpplayLinkControl.sendOtherBeantoJSon(HpplayAPISDKActivity.this, 19, webPushList, 1);
                bAutoSendClickFlag=true;
                break;

            case R.id.buttonsenduser:
                List<WebPushInfo> webPushuserList = new ArrayList<WebPushInfo>();
                WebPushInfo webPushInfo = new WebPushInfo();
                webPushInfo.setContent(mEditTextUser.getText().toString());
                webPushInfo.setUserid("111111");
                webPushInfo.setName("2222222222");
                webPushInfo.setTextsize(50);
                webPushInfo.setDelaytime(0);
                webPushInfo.setPadding(10);
                webPushInfo.setType(1);
                webPushInfo.setWebpushid(1 + "");
                webPushInfo.setFontColor("ffffff");
                webPushInfo.setBordercolor("ffffff");
                webPushInfo.setUnderlineColor("ffffff");
                webPushInfo.setShadowColor("ffffff");
                webPushuserList.add(webPushInfo);
                mHpplayLinkControl.sendOtherSingleBeantoJSon(HpplayAPISDKActivity.this, 20, webPushInfo, 1);
                bAutoSendClickFlag=true;
                break;
            default:
                break;
        }
    }

    @Override
    public void onDeviceCallback(Object object) {
        mVideoInfo = (MediaStateInfo) object;
        mHandler.sendEmptyMessage(2);
    }

    /**
     * 刷新到UI线程
     */
    @Override
    public void onResultDate(Object arg0, int arg1) {
        switch (arg1) {
            case 1:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 2:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 3:
                isConnect = (Boolean) arg0;
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 4:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 5:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 6:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 7:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 8:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 9:
                //isBack = isBack ? false : true;
                //showCurseDialog(isBack?"当前为后台成功":"当前为前台播放");
                break;

            case 10:
                isPlay = (Boolean) arg0;
                showCurseDialog(isPlay?"播放成功":"播放失败");
                break;

            case 11:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 12:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 13:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 14:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 15:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 16:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 17:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 18:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            case 19:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;
            case 20:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;
            case 21:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;
            case 22:
                showCurseDialog((Boolean) arg0?"成功":"失败");
                break;

            default:
                break;
        }

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mHpplayLinkControl.dismissHpplayWindow();
    }

    @Override
    public void onTransportData(Object o) {
        String s = (String) o;
        Log.e(TAG,"------"+s);
    }

    @Override
    public void onAuthorizationCode(AuthorizationCodeCallBack authorizationCodeCallBack) {
        Log.e(TAG,"-------onAuthorizationCode---------");
        mAuthorizationCodeCallBack = authorizationCodeCallBack;
        mHandler.sendEmptyMessage(5);
//        authorizationCodeCallBack.onAuthorizationCode("1234");

    }



    @Override
    public void onConnectRefuse(int i) {
        mHandler.sendEmptyMessage(4);
        Log.e(TAG,"-------onConnectRefuse---------"+i);
    }

    private void setCastView(){
        View view = View.inflate(this, R.layout.hpplay_deivce_list_layout, null);

        mListView = (ListView) view.findViewById(R.id.hpplay_fragment_listview);
        mDeviceAdapter = new DeviceAdapter(this);
        mListView.setAdapter(mDeviceAdapter);

        mDeviceAdapter.setListNotify(mListDevice,mPosition);
        View headerView = View.inflate(this, R.layout.hpplay_list_item_layout, null);
        TextView deviceName = (TextView) headerView.findViewById(R.id.item_textview);
        ImageView typeImg = (ImageView) headerView.findViewById(R.id.item_type_progresbar);
        typeImg.setImageResource(R.drawable.hpplay_phone_icon);
        deviceName.setText(Build.MODEL + "");
        headerView.findViewById(R.id.item_progresbar).setVisibility(View.GONE);
        mSelectImg = (ImageView) headerView.findViewById(R.id.item_imageview);
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSelectImg.setSelected(true);
                mSelectImg.setVisibility(View.VISIBLE);
                mPosition = -1;
                if(mDeviceAdapter != null){
                    mDeviceAdapter.setNotifyConnectState(2);
                }
                mHpplayLinkControl.stopPlay(null, 0);
                mHpplayLinkControl.castDisconnectDevice();
            }
        });

        if (isFirstConnect) {
            mSelectImg.setSelected(true);
            mSelectImg.setVisibility(View.VISIBLE);
        }

        mListView.addHeaderView(headerView);


        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try{
                    if (position > 0) {
                        mPosition = position - 1;
                        if(mHpplayLinkControl.getMirrorState() &&
                                mListDevice.get(mPosition).getDeviceIp().equals(mHpplayLinkControl.getCastDeviceInfo().getDeviceIp()) ){
                            return;
                        }
                        mSelectImg.setVisibility(View.GONE);
                        mDeviceAdapter.setSelectItem(mPosition);
                        mHpplayLinkControl.castConnectDevice(mListDevice.get(position - 1),null);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }


    private void showCurseDialog(String msg) {

        try {
            int dialogW = 0;
            int dialogH = 0;

            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                dialogW = mWidth - 210;
                dialogH = mHeigh - 800;
            } else {
                dialogW = mWidth - 800;
                dialogH = mHeigh - 800;
            }


            View view = View.inflate(this, R.layout.hpplay_dialog_full_layout, null);
            TextView textView = (TextView) view.findViewById(R.id.text_log);

            textView.setText(msg);
            final CustomDialog dialog = new CustomDialog.Builder(this)
                    .setDiglogMatrix(dialogW, dialogH)
                    .setContentView(view)
                    .create();
            dialog.show();

            View installLayout = view.findViewById(com.happly.link.R.id.hpplay_install_layuot);
            TextView dialogTx = (TextView) view.findViewById(com.happly.link.R.id.hpplay_dialog_bt_tx);
            installLayout.setVisibility(View.VISIBLE);
            installLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
            });

            dialogTx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public  String getLocalIpAddress() {
        if(mHpplayLinkControl.getContext() == null){
            return "NULL";
        }
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            return "NULL";
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ip = wifiInfo.getIpAddress();
        return  (ip & 0xFF ) + "." + ((ip >> 8 ) & 0xFF) + "." + ((ip >> 16 ) & 0xFF) + "." + ( ip >> 24 & 0xFF) ;
    }
}
